import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PriceCalculator {
    public static void main(String[] args) {
        String filePath = "products.txt"; 
        double totalPrice = 0;
        int itemCount = 0;

        // 正则表达式提取价格
        Pattern pricePattern = Pattern.compile(",(\\d+)元/台");

        try (Scanner scanner = new Scanner(new InputStreamReader(new FileInputStream(filePath)))) {
            if (scanner.hasNextLine()) {
                scanner.nextLine(); 
            }
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                Matcher matcher = pricePattern.matcher(line);
                if (matcher.find()) {
                    double price = Double.parseDouble(matcher.group(1));
                    totalPrice += price;
                    itemCount++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        double averagePrice = itemCount > 0 ? totalPrice / itemCount : 0;

        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filePath, true)))) {
            writer.println("平均价格: " + averagePrice + "元/台");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("计算完成，平均价格已写入文件。");
    }
}
